﻿using System;
using System.Collections.Generic;
using HarmonyLib;
using BepInEx;
using KBEngine;
using System.Linq;
using BepInEx.Logging;
using GUIPackage;
using JSONClass;
using System.Reflection.Emit;
using System.Diagnostics;

namespace zrgMod;

[BepInPlugin("zrgMod", "zrgMod", "1.0.0")]
public partial class Plugin : BaseUnityPlugin
{
    public static ManualLogSource LogSource;

    private void Start()
    {
        LogSource = base.Logger;
        Harmony.CreateAndPatchAll(typeof(Plugin), "zrgMod");
    }

    [HarmonyPostfix, HarmonyPatch(typeof(MainUICreateAvatar), nameof(MainUICreateAvatar.CreateFinsh))]
    public static void MainUICreateAvatar_CreateFinsh_Postfix()
    {

    }

    [HarmonyPostfix, HarmonyPatch(typeof(LunDaoHuiHe), nameof(LunDaoHuiHe.Init))]
    public static void LunDaoHuiHe_Init_Postfix(LunDaoHuiHe __instance)
    {
        // 玩家拥有天赋【殇道初明】：论道回合+1
        if (PlayerEx.HasTianFu(690001))
        {
            __instance.totalHui++;
            __instance.shengYuHuiHe = __instance.totalHui - __instance.curHui;
            Traverse.Create(__instance).Method("upDateHuiHeText").GetValue();
        }
    }

    [HarmonyTranspiler, HarmonyPatch(typeof(GUIPackage.item), nameof(GUIPackage.item.gongneng))]
    public static IEnumerable<CodeInstruction> GUIPackage_item_gongneng_Transpiler(
        IEnumerable<CodeInstruction> instructions,
        ILGenerator ilGenerator)
    {
        var ops = instructions.ToList();

        /*
586 | 07BE | ldloc.s V_27 (27)
587 | 07C0 | ldc.i4.0
588 | 07C1 | bge.s 591
589 | 07C3 | ldc.i4.0
590 | 07C4 | stloc.s V_27 (27)
591 | 07C6 | ldloc.s	V_26 (26)
592 | 07C8 | ldloc.s	V_27 (27)
593 | 07CA | callvirt	instance void KBEngine.Avatar::AddDandu(int32)
        */

        // 593
        var idx = ops.FindIndex(0, i => i.Calls(AccessTools.Method(typeof(Avatar), nameof(Avatar.AddDandu))));
        if (idx == -1)
        {
            return ops.AsEnumerable();
        }

        // 591
        var idx2 = idx - 2;

        // 588
        var idx3 = idx - 5;

        var label2 = ilGenerator.DefineLabel();
        ops[idx2].labels.Add(label2);

        var newLabel = ilGenerator.DefineLabel();
        ops[idx3].operand = newLabel;

        // 玩家拥有天赋【净丹仙贝】：服用废丹后免疫丹毒
        ops.InsertRange(idx2, new List<CodeInstruction>(){
            new (OpCodes.Ldarg_0) { labels = new List<Label>() { newLabel } },
            new (OpCodes.Call, AccessTools.Method(typeof(Plugin), nameof(Plugin.CheckTianFu690051), new Type[] { typeof(GUIPackage.item) })),
            new (OpCodes.Brfalse_S, label2),
            new (OpCodes.Ldc_I4_0),
            new (OpCodes.Stloc_S, 27)
        });

        return ops.AsEnumerable();
    }

    public static bool CheckTianFu690051(GUIPackage.item item)
    {
        return _ItemJsonData.DataDict[item.itemID].ItemFlag.Contains(50)
            && PlayerEx.HasTianFu(501) && PlayerEx.HasTianFu(690051);
    }
}
